package com.easywan.util;

import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import javax.imageio.ImageIO;

import org.omg.CORBA.portable.OutputStream;
import org.springframework.util.SystemPropertyUtils;

public class ImageUtils {
	/**
	 * 将图片写到file中
	 * @param img
	 * @param file
	 * @throws IOException
	 */
	private static void wirte(BufferedImage img,File file) throws IOException{
		 ImageIO.write(img, "JPEG", file);
	}
	private static BufferedImage drawImg(InputStream is) throws IOException{
		BufferedImage bi = ImageIO.read(is);
		return bi;
	}
	private static BufferedImage drawImg(File is) throws IOException{
		BufferedImage bi = ImageIO.read(is);
		return bi;
	}
	public static Boolean scala(InputStream f,int width,File to) throws IOException{
		 BufferedImage bi = ImageIO.read(f);
		 if(width < bi.getWidth()){
			 double ratio = width * 1.0 / bi.getWidth();
			 Image itemp = null;//bi.getScaledInstance(width, (int)(bi.getHeight() * ratio), bi.SCALE_SMOOTH);
			 AffineTransformOp op = new AffineTransformOp(AffineTransform
                     .getScaleInstance(ratio, ratio), null);
             itemp = op.filter(bi, null);
             wirte((BufferedImage) itemp,to);
		 }else{
			 wirte(bi,to);
		 }
		 return true;
	}
	public static Boolean save(String imageUrls, String string,int w) throws  IOException {
		try{ 
		URL url = new URL(imageUrls);    
	     HttpURLConnection conn = (HttpURLConnection)url.openConnection();    
	                //设置超时间为3秒  
        conn.setConnectTimeout(3*1000);  
        //防止屏蔽程序抓取而返回403错误  
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");  
        //得到输入流  
	     InputStream inputStream = conn.getInputStream();    
		File image = new File(string);
		if(!image.exists()){
			image.mkdirs();
		}
		//System.out.println(image.getAbsolutePath());
		return scala(inputStream,w,image);
		
		}catch(FileNotFoundException e){
			return false;
		}
		
	}
}
